//
//  String+Extension.swift
//  SK_BasePrivateProject
//
//  Created by Regina on 2018/7/8.
//  Copyright © 2018年 leapp. All rights reserved.
//

import UIKit

extension String {
    ///判断字符串是否为空
    func isBlank() -> Bool {
        
        var newString = self;
        
        if newString.isEmpty {
            return true
        }
        
        newString = newString.trimmingWhiteSpaceCharacters()
        
        if newString.isEmpty {
            return true
        }
        return false
    }
    
    ///判断是否是手机号
    func isMobilePhoneNumber() -> Bool {
        
        let mobile = "^1((3[0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\\d{8}$)"
        
        let  CM = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
        
        let  CU = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
        
        let  CT = "(^1(33|53|71|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
        
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
        let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU)
        let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT)
        
        if ((regextestmobile.evaluate(with: self) == true)
            || (regextestcm.evaluate(with: self)  == true)
            || (regextestct.evaluate(with: self) == true)
            || (regextestcu.evaluate(with: self) == true)) {
            return true
        } else {
            return false
        }
    }
    
    ///判断密码是否数字和字母组合组成， 默认6-16位
    func isAccount(number: Int = 11) -> Bool {
        
        let rule = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{" + String(number) + "}$"
        let regextestAccount = NSPredicate(format: "SELF MATCHES %@",rule)
        if (regextestAccount.evaluate(with: self) == true) {
            return true
        } else {
            return false
        }
    }
    
    ///判断密码是否数字和字母组合组成， 默认6-16位
    func isPassword(minNumber: Int = 6, maxNumber: Int = 16) -> Bool {
        
        let rule = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{" + String(minNumber) + "," + String(maxNumber) + "}$"
        let regextestpwd = NSPredicate(format: "SELF MATCHES %@",rule)
        if (regextestpwd.evaluate(with: self) == true) {
            return true
        } else {
            return false
        }
    }
    
    ///判断是否是邮箱
    func isEmail() -> Bool {
        
        let rule = "^([a-z0-9_//.-]+)@([//da-z//.-]+)//.([a-z//.]{2,6})$"
        let regextestpwd = NSPredicate(format: "SELF MATCHES %@",rule)
        if (regextestpwd.evaluate(with: self) == true) {
            return true
        } else {
            return false
        }
    }
    
    ///判断是否包含表情
    func containsEmoji() -> Bool {
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x1F600...0x1F64F, // Emoticons
            0x1F300...0x1F5FF,      // Misc Symbols and Pictographs
            0x1F680...0x1F6FF,      // Transport and Map
            0x2600...0x26FF,        // Misc symbols
            0x2700...0x27BF,        // Dingbats
            0xFE00...0xFE0F:        // Variation Selectors
                return true
            default:
                continue
            }
        }
        return false
    }
    
    //String转化
   static func stringToFloat(str:String)->(CGFloat){
        let string = str
        var cgFloat:CGFloat = 0
        if let doubleValue = Double(string){
            cgFloat = CGFloat(doubleValue)
        }
        return cgFloat
    }
    
    
   static func stringToInt(str:String)->(Int){
        let string = str
        var int:Int?
        if let doubleValue = Int(string) {
            int = Int(doubleValue)
        }
        if int == nil{
            return 0
        }
        return int!
    }

    
    ///去掉字符串中的空格及换行符
    func trimmingWhiteSpaceCharacters() -> String {
        
        var newString = self;
        newString = newString.trimmingCharacters(in: CharacterSet.init(charactersIn: "\r"))
        newString = newString.trimmingCharacters(in: CharacterSet.init(charactersIn: "\n"))
        newString = self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        newString = self.trimmingCharacters(in: CharacterSet.init(charactersIn: " "))
        return newString;
    }
    
    ///去掉字符串中的特殊字符
    func trimmingSpecialCharacters() -> String {
        
        var newString = self;
        let charactersSet: CharacterSet = CharacterSet.init(charactersIn: "@／:：;；()（）!！,，.。¥￥“”‘’//「」＂、【】[]{}｛｝—～《》… <>?？#%-*+=_\\|~＜＞$€^·\'#$%^&*()_+'\"");
        newString = newString.trimmingCharacters(in: charactersSet);
        return newString;
    }
    
    ///去掉字符串中的表情
    func trimmingEmojiCharacters() -> String {
        
        var newString = self;
        
        let regex = try!NSRegularExpression.init(pattern: "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]", options: .caseInsensitive)
        
        newString = regex.stringByReplacingMatches(in: newString, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange.init(location: 0, length: newString.count), withTemplate: "")
        
        return newString;
    }
    
    
//字符串截取
    var length: Int {
        return self.characters.count
    }
    
    subscript (i: Int) -> String {
        return self[i ..< i + 1]
    }
    
    func substring(fromIndex: Int) -> String {
        return self[min(fromIndex, length) ..< length]
    }
    
    func substring(toIndex: Int) -> String {
        return self[0 ..< max(0, toIndex)]
    }
    
    subscript (r: Range<Int>) -> String {
        let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound))))
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(start, offsetBy: range.upperBound - range.lowerBound)
        return String(self[start ..< end])
    }
}

// MARK: - 
extension String {
    /// 指定颜色的 attributated string
    static func attribuateOK(_ string: String, color: UIColor = TCM_HexRGB(0x693C26)) -> NSAttributedString {
        let attribute = [NSAttributedStringKey.foregroundColor: color]
        return NSAttributedString(string: string, attributes: attribute)
    }
    
    static func attribuateBack(_ string: String, color: UIColor = TCM_HexRGB(0x5C5C5C)) -> NSAttributedString {
        let attribute = [NSAttributedStringKey.foregroundColor: color]
        return NSAttributedString(string: string, attributes: attribute)
    }
    
    static func attribuateTitle(_ string: String, color: UIColor = TCM_HexRGB(0x3B3B3B)) -> NSAttributedString {
        let attribute = [NSAttributedStringKey.foregroundColor: color]
        return NSAttributedString(string: string, attributes: attribute)
    }
    
    static func attribuateMessage(_ string: String, color: UIColor = TCM_HexRGB(0x4A90E2)) -> NSAttributedString {
        let attribute = [NSAttributedStringKey.foregroundColor: color]
        return NSAttributedString(string: string, attributes: attribute)
    }

    /// 返回指定 lineHeightMultiple 的字符串
    static func attribute(_ string: String, lineHeightMultiple: CGFloat) -> NSAttributedString {
        let paragraph = NSMutableParagraphStyle()
        paragraph.lineHeightMultiple = lineHeightMultiple
        return NSMutableAttributedString(string: string, attributes: [NSAttributedStringKey(rawValue: NSAttributedStringKey.paragraphStyle.rawValue): paragraph])
    }
}

// MARK: - 字符串形式的秒数转换成 mm:ss 格式
extension String {
    static func videoLengthFormat(length: Int = 0) -> String {
//        let oneMin = 60
//        let anHour = 60 * 60
//
//        let minutes = length / 60
//        let hours = minutes / 60
//
//        switch length {
//        case 0 ..< oneMin: // 小于一分钟
//            return "00:\(length)"
//        case 60 ..< anHour: // 大于一分钟小于一小时
//            return "\(minutes):\(length % oneMin)"
//        default:
//            // 大于一分钟小于一小时
//            return "\(hours):\(minutes):\(length % oneMin)"
//        }
        
        if length < 60 {
            return String(format: "00:%.2d", length)
        } else {
            return String(format: "%.2d:%.2d", length / 60, length % 60)
        }
    }
}

